package gecko.dingtalk;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.taobao.api.ApiException;
import gecko.AbstractInterceptor;
import gecko.GeckoContext;
import gecko.GeckoScoped;
import gecko.lang.TypedMap;
import gecko.x.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 监听系统异常信息，并通过群机器人
 *
 * @author 陈永佳 (yoojiachen@gmail.com)
 * @version 0.0.1
 */
public class DingTalkErrorReportRobot extends AbstractInterceptor {

    private static final Logger LOGGER = LoggerFactory.getLogger(DingTalkErrorReportRobot.class);

    private DingTalkClient mDingTalkRobot;

    private boolean enabled = true;
    private String mKeyTime;
    private String mKeyDevSN;
    private String mKeyAddr;
    private String mKeyReason;

    @Override
    public void onInit(TypedMap initArgs, GeckoScoped scoped) {
        super.onInit(initArgs, scoped);
        final String token = initArgs.getString("robotToken");
        if (Strings.isNullOrEmpty(token)) {
            LOGGER.debug("钉钉报告机器人未设置Token： 停用");
            enabled = false;
        } else {
            enabled = true;
            mKeyTime = initArgs.getString("fieldTime", "时间");
            mKeyDevSN = initArgs.getString("fieldSN", "序列");
            mKeyAddr = initArgs.getString("fieldAddr", "地址");
            mKeyReason = initArgs.getString("fieldReason", "原因");
            LOGGER.debug("钉钉报告机器人启用： {}", token);
            mDingTalkRobot = new DefaultDingTalkClient("https://oapi.dingtalk.com/robot/send?access_token=" + token);
        }
    }

    @Override
    public void handle(GeckoContext context, GeckoScoped scoped) throws Exception {
        if (!enabled) {
            return;
        }
        TypedMap info = TypedMap.wrap(context.inbound().data());
        scoped.submit(() -> {
            OapiRobotSendRequest request = new OapiRobotSendRequest();
            request.setMsgtype("markdown");
            OapiRobotSendRequest.Markdown markdown = new OapiRobotSendRequest.Markdown();
            markdown.setTitle("设备报警");
            markdown.setText("## 设备报警\n" +
                    "- 发生时间： " + info.getString(mKeyTime) + "\n" +
                    "- 设备编号： " + info.getString(mKeyDevSN) + "\n" +
                    "- 内部地址： " + info.getString(mKeyAddr) + "\n" +
                    "- 故障原因： " + info.getString(mKeyReason) + "\n");
            request.setMarkdown(markdown);
            try {
                OapiRobotSendResponse response = mDingTalkRobot.execute(request);
                LOGGER.debug("钉钉系统响应： {}", response.getErrmsg());
            } catch (ApiException e) {
                LOGGER.debug("钉钉机器人出错", e);
            }
        });

    }
}
